package BLC

import (
	"bytes"
	"crypto/elliptic"
	"encoding/gob"
	"fmt"
	"io/ioutil"
	"log"
	"os"
)

const walletFile  = "Wallets.dat"

type Wallets struct {
	WalletsMap map[string]*Wallet
}

//创建钱包集合,如果本地存在本地取
func NewWallets() (*Wallets ,error) {

	if _,err := os.Stat(walletFile); os.IsNotExist(err){
		Wallets := &Wallets{}
		Wallets.WalletsMap = make(map[string]*Wallet)
		return Wallets, err
	}

	fileContent, err := ioutil.ReadFile(walletFile)
	if err != nil {
		log.Panic(err)
	}

	var wallets Wallets
	gob.Register(elliptic.P256())
	decoder := gob.NewDecoder(bytes.NewReader(fileContent))
	err = decoder.Decode(&wallets)
	if err != nil {
		log.Panic(err)
	}

	return &wallets,nil
}

//创建一个钱包
func (w *Wallets) CreateNewWallet()  {

	wallet := NewWallet()
	fmt.Printf("wallet address: %s\n",wallet.GetAddress())
	w.WalletsMap[string(wallet.GetAddress())] = wallet

	// 进行保存
	w.SavaWallets()
}

func (w *Wallets) SavaWallets()  {
	var content bytes.Buffer

	// 注册的魔都是为了可以序列化所有类型（包括interface）
	gob.Register(elliptic.P256())

	encode := gob.NewEncoder(&content)
	err := encode.Encode(&w)
	if err != nil {
		log.Panic(err)
	}

	// 将序列化的数据写入到文件，
	err = ioutil.WriteFile(walletFile,content.Bytes(),0644)

}

